package cn.edu.nyist.integration.service.impl;

import cn.edu.nyist.integration.common.Const;
import cn.edu.nyist.integration.common.ResponseCode;
import cn.edu.nyist.integration.common.ServerResponse;
import cn.edu.nyist.integration.entity.IntegralItem;
import cn.edu.nyist.integration.entity.Integration;
import cn.edu.nyist.integration.mapper.IntegralItemMapper;
import cn.edu.nyist.integration.mapper.IntegrationMapper;
import cn.edu.nyist.integration.mapper.UserMapper;
import cn.edu.nyist.integration.service.IntegrationService;
import cn.edu.nyist.integration.util.RedisUtil;
import cn.edu.nyist.integration.vo.UserCreditVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class IntegrationServiceImpl implements IntegrationService {
    @Resource
    private IntegrationMapper integrationMapper;
    @Resource
    private IntegralItemMapper itemMapper;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 根据id查询用户的个人积分
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Integration> selectById(Long userId) {
        if (userId == null){
            return ServerResponse.createByErrorMessage(Const.ILLEGAL_ARGUMENT);
        }
        //用户查询自己的积分可能会频繁一些，将用户的积分也加到redis中，首先从redis查积分，有的话直接返回
        Integration redisIntegration = (Integration) redisUtil.get("userScore"+userId);
        if (redisIntegration != null){
            return ServerResponse.createBySuccessData(redisIntegration);
        }

        Integration integration = integrationMapper.selectByUserId(userId);
        //如果这时候查到的结果是null那么就是此用户还没有积分，这时我们返回友好提示
        if (integration == null){
            return ServerResponse.createBySuccessMessage("您还没有在本超市消费过，积分为0");
        }

        //第一次查询缓存中是没有用户积分的，所以需要将积分加入缓存
        redisUtil.set("userScore"+userId,integration);

        return ServerResponse.createBySuccessData(integration);
    }

    /**
     * 查询积分排名
     * @param pageNum
     * @param pageSize
     * @param username
     * @return
     */
    @Override
    public PageInfo selectRank(int pageNum, int pageSize, String username) {
        if (username!=null){
            username = "%"+ username +"%";
        }
        PageHelper.startPage(pageNum, pageSize);
        List<UserCreditVO> voList = integrationMapper.selectRank(username);
        PageInfo pageInfo = new PageInfo(voList);
        pageInfo.setList(voList);
        return pageInfo;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ServerResponse updateTotalAndInsertRecord(IntegralItem item) {

        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        //插入记录
        int i = itemMapper.insert(item);
        if (i==0){
            throw new RuntimeException("插入明细失败");
        }
        //根据用户名查ID
        String uid = userMapper.selectIdByUsername(item.getUsername());

        long userId = Long.parseLong(uid);
        //不管下面进行是增加积分还是修改总积分都要先把用户积分的缓存清一下，再修改
        redisUtil.del("userScore"+uid);

        //获取这次操作的总分数
        Integer newScore = item.getIntegralSum();

        //首先判断用户是不是首次获得积分，如果是第一次就插入数据，否则更新原有的积分
        Integration integration = integrationMapper.selectByUserId(userId);
        if (integration == null){
            //这时插入数据

            Integration init = init(new Integration(), newScore, userId);
            int insert = integrationMapper.insertSelective(init);
            if (insert == 0){
                throw new RuntimeException("第一次插入积分失败");
            }
        }else {
            //修改当前用户的总分数 总分数=上一次分数+这次操作的分数
            int row = integrationMapper.updateTotalScore(newScore, userId);
            if (row == 0){
               throw new RuntimeException("修改总积分失败");
            }
        }

        return ServerResponse.createBySuccess();
    }

    /**
     * 获取会员积分增加详情
     * @param pageNum
     * @param pageSize
     * @param username
     * @return
     */
    @Override
    public PageInfo getDetailList(int pageNum, int pageSize, String username){
        PageHelper.startPage(pageNum, pageSize);
        List<IntegralItem> itemList = itemMapper.selectAllByUsername(username);
        PageInfo pageInfo = new PageInfo(itemList);
        pageInfo.setList(itemList);
        return pageInfo;
    }


    private Integration init(Integration integration,int totalScore,Long userId){
        System.out.println("userId="+userId);
        integration.setUserId(userId);
        integration.setTotalScore(totalScore);
        integration.setBeforeScore(0);
        integration.setAfterScore(totalScore);
        integration.setOperateScore(totalScore);
        integration.setCreateTime(new Date());
        integration.setUpdateTime(new Date());

        return integration;
    }

    /**
     * 用户根据id查询积分排名
     */
    @Override
    public ServerResponse<UserCreditVO> queryScoreRank(Long userId){
        if (userId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENTS.getCode(),"非法参数");

        }
       UserCreditVO userCreditVO = integrationMapper.queryRankByUserId(userId);
        return ServerResponse.createBySuccessData(userCreditVO);
    }


}
